package com.runen.infinitemovement.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.entity.SportsStopEntity;
import com.runen.infinitemovement.widget.popupwind.AchievementPoppupWindow;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.rxnetlibrary.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class StopSportsActivity extends BaseActivity {
    @BindView(R.id.ll_publish)
    LinearLayout llPublish;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.ll_share)
    LinearLayout llShare;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.iv_finish)
    ImageView ivFinish;
    private AchievementPoppupWindow poppupWindow;
    private static String imgUrl;
    String motionId;
    private SportsStopEntity stopEntity;
    private static StopSportsActivity activity;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sports_stop;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        activity = this;
//        imgUrl = getIntent().getStringExtra("imgUrl");
        motionId = getIntent().getStringExtra("motionId");
        imgUrl = String.format(Constant.IMG_SPORT_RECORD, motionId);
        webSetting(webView);
        webView.loadUrl(String.format(Constant.SPORTS_DETAILS, motionId));
    }

    String medal;

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (TextUtils.isEmpty(medal)) {
            medal = getIntent().getStringExtra("medal");
            if (!TextUtils.isEmpty(medal)) {
                stopEntity = JsonUtils.fromJson(medal, SportsStopEntity.class);
                List<SportsStopEntity.DataBean.SportMedalsBean> list = new ArrayList<>();
                //整理数据
                if (stopEntity.data != null) {
                    if (stopEntity.data.personalLongMarchProgress != null) {
                        SportsStopEntity.DataBean.SportMedalsBean sportMedalsBean = new SportsStopEntity.DataBean.SportMedalsBean();
                        sportMedalsBean.personalLongMarchProgress = stopEntity.data.personalLongMarchProgress;
                        list.add(sportMedalsBean);
                    }
                    if (stopEntity.data.sportMedals != null && stopEntity.data.sportMedals.size() > 0) {
                        list.addAll(stopEntity.data.sportMedals);
                    }
                }
                if (list != null && list.size() > 0) {
                    showPopup(list);
                }
            }
        }

    }

    private void showPopup(List<SportsStopEntity.DataBean.SportMedalsBean> stopEntity) {
        poppupWindow = AchievementPoppupWindow.getInstance(this, stopEntity);
        poppupWindow.show();
    }


    @OnClick({R.id.ll_publish, R.id.ll_share, R.id.iv_finish})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_publish:
                Intent intent = new Intent(this, PublishStatusActivity.class);
                intent.putExtra("imgUrl", imgUrl);
                intent.putExtra("PUBLISH_FLAG", 1);
                intent.putExtra("motionId", motionId);
                startActivity(intent);
                break;
            case R.id.ll_share:
                showSharePopup();
                break;
            case R.id.iv_finish:
                finish();
                break;
        }
    }

    private void showSharePopup() {
        SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(this, "我在无涯运动跑步，今天离长征会师更进一步。",
                "体验不一样的长征路，与我一起挑战吧！", String.format(Constant.SPORTS_DETAILS2, motionId, "WEB"));
        sharePoppupWindow.show();
    }


    /**
     * WebView设置参数
     *
     * @param webView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private static void webSetting(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true);// 设置允许访问文件数据
        settings.setSupportMultipleWindows(true);
        webView.setWebChromeClient(new WebViewClientLoad());
        settings.setBlockNetworkImage(false);//同步请求图片
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        webView.addJavascriptInterface(new MyJavascriptInterface(), "android");
    }

    /**
     * 接口回调
     */
    private static class WebViewClientLoad extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            activity.showDialog();
            if (newProgress == 100) {
                activity.dismissDialog();
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    //要用来被js调用的java对象
    public static class MyJavascriptInterface {
        @JavascriptInterface
        public void onPublish(String sportRecordId) {
            publish(sportRecordId);
        }

        @JavascriptInterface
        public void onShare(String sportRecordId) {
            share(sportRecordId);
        }

        @JavascriptInterface
        public void close() {

//            EventBus.getDefault().post(new EventWebEntity(4));
        }

        @JavascriptInterface
        public void showDialog() {
//            EventBus.getDefault().post(new EventWebEntity(3));
        }

        @JavascriptInterface
        public void dismissDialog() {
//            EventBus.getDefault().post(new EventWebEntity(1));
        }
    }

    public static void share(String sportRecordId) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                Message msg = new Message();
                Bundle bundle = new Bundle();
                bundle.putString("sportRecordId", sportRecordId);
                msg.what = 1;
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });
    }

    public static void publish(String sportRecordId) {
        Intent intent = new Intent(activity, PublishStatusActivity.class);
        intent.putExtra("imgUrl", imgUrl);
        intent.putExtra("PUBLISH_FLAG", 1);
        intent.putExtra("motionId", sportRecordId);
        activity.startActivity(intent);
    }

    private static Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String sportRecordId = bundle.getString("sportRecordId");
                    SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(activity, "我在无涯运动跑步，今天离长征会师更进一步。",
                            "体验不一样的长征路，与我一起挑战吧！", String.format(Constant.SPORTS_DETAILS2, sportRecordId, "WEB"));
                    sharePoppupWindow.show();
                    break;
            }
            return false;
        }
    });
}
